package middleware

import (
	"net/http"

	"gitee.com/zatto/project/tree/master/vblog/api/apps"
	"gitee.com/zatto/project/tree/master/vblog/api/apps/user"
	"github.com/gin-gonic/gin"
)

func AuthFunc(c *gin.Context) {
	// 从cookie里获取username
	ck, err := c.Request.Cookie("username")
	if err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{"msg": err.Error()})
		c.Abort()
		return
	}
	username := ck.Value

	// 从cookie里获取session
	ck, err = c.Request.Cookie("session")
	if err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{"msg": err.Error()})
		c.Abort()
		return
	}

	session := ck.Value
	// 判断用户是否登录
	svc := apps.GetInternalApp(user.AppName).(user.Service)
	err = svc.CheckIsLogin(c.Request.Context(), user.NewCheckIsLogin(username, session))
	if err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{"msg": err.Error()})
		c.Abort()
		return
	}
	c.Next()
}
